bl_info = {
    "name": "TCP Server",
    "author": "会飞的键盘侠",
    "version": (0, 0, 1),
    "blender": (3, 0, 0),
    "location": "3DView->UI",
    "category": "自定义组"
}

# 如何实现 外部tcp控制blender?
# 1. 在blender上部署tcp server
# 2. 外部使用 tcp client 连接
# 3. 外部发送需要操作的指令给blender
# 4. server处理命令后 返回给 外部的client
{"OP_TYPE": {}, "DATA":{}}
# 如何优化?
# 1. 使用固定的几种操作规定, 简化tcp通信
# 2. 使用 rpc 协议(同1), 更加方便api接口定制 grpc

import bpy
from .server import Conn


class RunServer(bpy.types.Operator):
    bl_idname = "tcp.server"
    bl_label = "Run Server"
    bl_description = "开启服务器"

    is_running = False

    def execute(self, context: bpy.types.Context):
        print("Server is Running!")
        wm = bpy.context.window_manager
        wm.modal_handler_add(self)
        self._timer = wm.event_timer_add(0.1, window=context.window)
        return {"RUNNING_MODAL"}

    def modal(self, context: bpy.types.Context, event):
        while not Conn.cmd.empty():
            cmd = Conn.cmd.get()
            try:
                value = eval(cmd)
            except Exception as e:
                value = str(e)
            Conn.value.put(value)
        return {"PASS_THROUGH"}


class ServerPanel(bpy.types.Panel):
    bl_idname = "SV_PT_UI"
    bl_label = "ServerPanel"
    bl_category = "服务器"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"

    def draw(self, context: bpy.types.Context):
        layout = self.layout
        layout.operator(RunServer.bl_idname)


reg, unreg = bpy.utils.register_classes_factory([RunServer, ServerPanel])


def register():
    reg()


def unregister():
    unreg()
